package com.zhilianbao.leyaogo.http.callback;

import android.content.Context;


import com.bql.convenientlog.CLog;
import com.bql.utils.CheckUtils;
import com.google.gson.Gson;
import com.zhilianbao.leyaogo.model.response.DownLoadResponse;
import com.zhilianbao.leyaogo.view.dialog.DownLoadProgressDialog;
import com.zhilianbao.okhttputils.request.BaseRequest;

import okhttp3.Response;

/**
 * 下载的进度回调
 */
public abstract class DownLoadCallback extends JsonCallback<DownLoadResponse> {

    private DownLoadProgressDialog mProgressDialog;//进度对话框


    public DownLoadCallback(Context context) {
        super(context);
        initPro(context);
    }


    /**
     * 初始化进度条对话框
     *
     * @param context
     */
    public void initPro(Context context) {
        if (mProgressDialog == null)
            mProgressDialog = new DownLoadProgressDialog(context);
        mProgressDialog.setCanceledOnTouchOutside(false);
    }

    /**
     * 显示进度对话框
     *
     * @param text 显示文本
     */
    public void showPro(String text,String max) {
        if (mProgressDialog != null && !mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }

        if (!CheckUtils.isEmpty(text)&& !CheckUtils.isEmpty(max))
            mProgressDialog.showText(text,max);
    }

    /**
     * dismiss进度对话框
     */
    public void dismissPro() {
        if (mProgressDialog != null && mProgressDialog.isShowing())
            mProgressDialog.dismiss();
    }

    @Override
    public void onBefore(BaseRequest request) {
        super.onBefore(request);
        showPro( "0%","0/100");

    }

    @Override
    public void onAfter(DownLoadResponse downLoadResponse, Exception e) {
        super.onAfter(downLoadResponse, e);
        dismissPro();
    }

    @Override
    public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
        super.upProgress(currentSize, totalSize, progress, networkSpeed);
        showPro(( (int) (100 * progress) + "%"),( (int) (100 * progress) + "/100"));
    }

    @Override
    public DownLoadResponse convertSuccess(Response response) throws Exception {
        String body = response.body().string();
        CLog.e("LogInterceptor", body);
        DownLoadResponse downLoadResponse = new Gson().fromJson(body, DownLoadResponse.class);
        if (downLoadResponse == null) {
            //解析错误
            return null;
        } else {
            return downLoadResponse;

        }
    }
}
